package com.zjq.authoritysystem.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zjq.authoritysystem.exception.CustomerAuthenticationException;
import com.zjq.authoritysystem.vo.result.Result;
import com.zjq.authoritysystem.vo.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Kimiaaaaa
 * @className LoginFailHandler
 * @Description 用户身份认证失败处理器
 * @date 2023-09-19 15:15
 */
@Slf4j
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        log.info("----------身份认证失败处理器启动");
        log.info("请求地址：" + request.getRequestURI());
        response.setContentType("application/json;charset=UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();

        String message;
        Integer code = 500;

        // 判断异常类型
        if (exception instanceof AccountExpiredException) {
            message = "账户已过期，登录失败！";
        } else if (exception instanceof BadCredentialsException) {
            message = "用户名或密码错误，登录失败！";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期，登录失败！";
        } else if (exception instanceof LockedException) {
            message = "账户已锁定，登录失败！";
        } else if (exception instanceof DisabledException) {
            message = "账户已禁用，登录失败！";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            message = "账户不存在，登录失败！";
        } else if (exception instanceof CustomerAuthenticationException) {
            message = exception.getMessage();
            code = 600;
        } else {
            message = "登录失败！";
        }

        // 将结果信息转换为JSON格式
        String result = JSON.toJSONString(Result.Error(code, message), SerializerFeature.DisableCircularReferenceDetect);
        log.info("结果：" + result);
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();

        log.info("----------身份认证失败处理器结束");
    }
}
